<?php

/**
 * 用户
 *
 * @author cdlei
 */

require_once 'CommonController.php';

class Admin_UserController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_User();
        $this->view->title = "管理中心";
    }

    /**
     * 默认动作
     * 
     * @return void
     */
    public function indexAction()
    {
        $partnerModel = new Application_Model_Partner();
        $userSessionModel = new Application_Model_UserSession();
        $time = time();

        //获取当前页码
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }

        //设置URL模板以及条件
        $urls = array();
        $vars = array();
        $wheres = array();

        $vars['userName'] = trim($this->_request->get('userName'));
        $vars['name'] = trim($this->_request->get('name'));
        $vars['mobile'] = trim($this->_request->get('mobile'));
        $vars['email'] = trim($this->_request->get('email'));
        $vars['partnerName'] = trim($this->_request->get('partnerName'));
        $vars['department'] = trim($this->_request->get('department'));
        $vars['status'] = trim($this->_request->get('status'));
        $vars['sort'] = $this->_request->get('sort') != NULL ? trim($this->_request->get('sort')) : 1;
        $urls = $vars;

        if ($vars['userName'] != '') {
            $wheres[] = "`u`.`userName` LIKE '%" . addslashes($vars['userName']) . "%'";
        }
        if ($vars['name'] != '') {
            $wheres[] = "`u`.`name` LIKE '%" . addslashes($vars['name']) . "%'";
        }
        if ($vars['mobile'] != '') {
            $wheres[] = "`u`.`mobile` LIKE '%" . addslashes($vars['mobile']) . "%'";
        }
        if ($vars['email'] != '') {
            $wheres[] = "`u`.`email` LIKE '%" . addslashes($vars['email']) . "%'";
        }
        if ($vars['partnerName'] != '') {
            if (strpos($vars['partnerName'], '耶客') !== FALSE || strtolower($vars['partnerName']) == 'yek') {
                $wheres[] = "`u`.`type` = 1";
            } else {
                $wheres[] = "`p`.`name` LIKE '%" . addslashes($vars['partnerName']) . "%'";
            }
        }
        if ($vars['department'] != '') {
            $wheres[] = "`u`.`department` LIKE '%" . addslashes($vars['department']) . "%'";
        }
        if ($vars['status'] == 1 || $vars['status'] == 2) {
            $wheres[] = "`u`.`status`  = '{$vars['status']}'";
        }
        if ($vars['sort'] == 1) {
            $orderBy = '`us`.`lastOnlineTime` DESC, `u`.`addTime` DESC';
        } else {
            $orderBy = '`u`.`addTime` DESC';
        }

        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $sql = "SELECT `u`.*, `p`.`name` AS `partnerName`, `us`.`lastOnlineTime` AS `lastOnlineTime` 
            FROM `{$this->_model->getTableName()}` AS `u` 
            LEFT JOIN `{$partnerModel->getTableName()}` AS `p` ON `u`.`partnerCode` = `p`.`code` 
            LEFT JOIN `{$userSessionModel->getTableName()}` AS `us` ON (`u`.`sessionId` = `us`.`id`)
            {$where} 
            ORDER BY {$orderBy}
        ";

        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();

        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;
        
        $rows = $dbPaginator->getRows();
        foreach($rows as $key=>$row) {
            $row['isOnline'] = $time - strtotime($row['lastOnlineTime']) > $this->_configs['project']['admin']['effectiveOnlineTime'] ? 0 : 1;
            $rows[$key] = $row;
        }

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        $this->view->rows = $rows;
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
        $this->view->vars = $vars;
    }
    /**
     * 解锁
     * 
     * @return void
     */    
    public function unlockAction()
    {
        $id = intval($this->_request->get('id'));
        if (empty($id)) {
             exit("没有传递参数ID");
        }
        $row = $this->_model->fetchRow("`id` = {$id}"); 
        if (empty($row)) {
             exit("没有找到记录。");
        }
        $this->_model->update(array('loginFailureNum' => 0,'loginFailureLastTime'=>'0000-00-00 00:00:00') , " `id` = '{$id}'" );
        $backUrl = $this->_request->get('backUrl') != NULL ? urldecode($this->_request->get('backUrl')) : @$_SERVER['HTTP_REFERER'];
        echo $this->view->message("操作成功。", $backUrl) ;
        exit;
    }    
    
    /**
     * 添加动作
     * 
     * @return void
     */
    public function insertAction()
    {
        //获取商家记录
        $partnerModel = new Application_Model_Partner();
        $userRoleModel = new Application_Model_UserRole();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $userRoleProductModel = new Application_Model_UserRoleProduct();
        $partnerRows = $partnerModel->fetchAll(NULL, "id desc");
        $this->view->partnerRows = $partnerRows;
        $this->view->partnerProductRows = $partnerProductModel->getAdapter()->fetchAll("SELECT `id`, `name`, `code`, `partnerCode` FROM `{$partnerProductModel->getTableName()}` ORDER BY `id` ASC");
        $this->view->partnerProductJsonData = Zend_Json::encode($this->view->partnerProductRows);

        if ($this->_request->isPost()) {
            $field = array();
            $filter = new Zend_Filter_StripTags();
            $field['userName'] = $filter->filter(trim($this->_request->getPost('userName')));
            $field['password'] = trim($this->_request->getPost('password'));
            $password2 = trim($this->_request->getPost('password2'));
            $field['status'] = intval($this->_request->getPost('status'));
            $field['name'] = $filter->filter(trim($this->_request->getPost('name')));
            $field['department'] = $filter->filter(trim($this->_request->getPost('department')));
            $field['mobile'] = $filter->filter(trim($this->_request->getPost('mobile')));
            $field['email'] = $filter->filter(trim($this->_request->getPost('email')));
            $field['type'] = (int)$filter->filter(trim($this->_request->getPost('type')));
            $field['partnerCode'] = $field['type'] == 2 ? $filter->filter(trim($this->_request->getPost('partnerCode'))) : '';
            $roleIds = (array) $this->_request->getPost('roleIds');
            $field['addTime']=date('Y-m-d H:i:s');
            $field['notes'] = $filter->filter(trim($this->_request->getPost('notes')));
            $field['addUserName'] = Application_Model_UserLogin::getInstance()->getLoginedUserName();

            if (strlen($field['userName']) > 50) {
                echo $this->view->message('用户名长度必须小于50个字符，请重新填写。') ;
                exit;
            }
            if (strlen($field['userName']) < 5) {
                echo $this->view->message('用户名长度不能小于5个字符，请重新填写。') ;
                exit;
            }
            if (!(preg_match("/^[a-zA-Z0-9]{2,20}$/", $field['userName']) || preg_match("/^[a-z]([a-z0-9]*[-_\.]?[a-z0-9]+)*@[a-z0-9]+([-_]?[a-z0-9]+)*(\.[a-z-0-9]{1,10})*$/i", $field['userName']))) {
                echo $this->view->message('用户名请填写英文字母、数字以及下划线，或填写E-Mail地址，请返回重新填写。') ;
                exit;
            }
            if ($this->_model->isExists($field['userName'])) {
                echo $this->view->message('用户名已经存在，请重新填写。') ;
                exit; 
            }
            if (strlen($field['password']) > 30 || strlen($field['password']) < 5) {
                echo $this->view->message('密码长度不在5-30范围内，请重新填写。') ;
                exit;
            }
            if ($field['password'] != $password2) {
                echo $this->view->message('确认密码填写错误。') ;
                exit;
            }
            if (strlen($field['name']) == 0) {
                echo $this->view->message('姓名不能为空，请重新填写。') ;
                exit;
            }
            if ($field['mobile'] != '') {
                if (!preg_match("|[0-9]{11}|", $field['mobile'])) {
                    echo $this->view->message('手机号码填写错误。') ;
                    exit;
                }
                if ($this->_model->isExists($field['mobile'])) {
                    echo $this->view->message('手机号已经被其他账户使用，请重新换一个。') ;
                    exit; 
                }
            }
            if ($field['email'] != '') {
                if (!preg_match("/^[a-z]([a-z0-9]*[-_\.]?[a-z0-9]+)*@[a-z0-9]+([-_]?[a-z0-9]+)*(\.[a-z-0-9]{1,10})+$/i", $field['email'])) {
                    echo $this->view->message('E-Mail地址填写错误。') ;
                    exit;
                }
                if ($this->_model->isExists($field['email'])) {
                    echo $this->view->message('E-Mail地址已经被其他账户使用，请重新换一个。') ;
                    exit; 
                }
            }
            if (empty($roleIds)) {
                echo $this->view->message('必须选择一个角色，请重新填写。') ;
                exit;
            }
            foreach($roleIds as $roleId) {
                $isAllProduct = $this->_request->getPost('roleIsAllProduct_' . $roleId) !== NULL ? 1 : 0;
                $userRoleProducts = $this->_request->getPost('userRoleProducts_' . $roleId);
                if ($isAllProduct == 0 && empty($userRoleProducts)) {
                    echo $this->view->message('在选择角色时，必须选择一个角色产品。');
                    exit;
                }
            }

            $field['password'] = md5($field['password']);
            $userId = $this->_model->insert($field);

            //添加角色
            foreach($roleIds as $roleId) {
                $userRoleField = array();
                $userRoleField['userId'] = $userId;
                $userRoleField['roleId'] = $roleId;
                $userRoleField['isAllProduct'] = $this->_request->getPost('roleIsAllProduct_' . $roleId) !== NULL ? 1 : 0;
                $userRoleModel->insert($userRoleField);
                if ($userRoleField['isAllProduct'] == 0) {
                    $userRoleProducts = (array) $this->_request->getPost('userRoleProducts_' . $roleId);

                    foreach($userRoleProducts as $userRoleProduct) {
                        $userRoleProductField = array();
                        $userRoleProductField['userId'] = $userId;
                        $userRoleProductField['roleId'] = $roleId;
                        $userRoleProductField['productCode'] = $userRoleProduct;
                        $userRoleProductModel->insert($userRoleProductField);
                    }
                }
            }

            echo $this->view->message('操作成功。', $this->view->projectUrl(array('action' => 'index'))) ;
            exit;
        }
    }

    /**
     * 更新动作
     * 
     * @return void
     */
    public function updateAction()
    {
        //获取商家记录
        $partnerModel = new Application_Model_Partner();
        $userRoleModel = new Application_Model_UserRole();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $userRoleProductModel = new Application_Model_UserRoleProduct();
        $partnerRows = $partnerModel->fetchAll(NULL, "id desc");
        $this->view->partnerRows = $partnerRows;
        $this->view->partnerProductRows = $partnerProductModel->getAdapter()->fetchAll("SELECT `id`, `name`, `code`, `partnerCode` FROM `{$partnerProductModel->getTableName()}` ORDER BY `id` ASC");
        $this->view->partnerProductJsonData = Zend_Json::encode($this->view->partnerProductRows);

        $id = intval($this->_request->get('id'));
        if (empty($id)) {
             exit("没有传递参数ID");
        }
        $row = $this->_model->fetchRow("`id` = {$id}"); 
        if (empty($row)) {
             exit("没有找到记录。");
        }

        //获取当前用户拥有的角色
        $existsRoleIds = array();
        $userRoleRows = $userRoleModel->fetchAll("`userId` = {$row['id']}");
        foreach($userRoleRows as $userRoleRow) {
            $existsRoleIds[] = $userRoleRow['roleId'];
        }

        //获取当前用户拥有的角色
        $userRoleRows = $userRoleModel->fetchAll("`userId` = {$row['id']}");

        //获取当前用户拥有的角色产品
        $userRoleProductRows = $userRoleProductModel->fetchAll("`userId` = {$row['id']}");

        //获取所有商家信息
        $partnerRows = $partnerModel->fetchAll(NULL, "id desc");

        $this->view->partnerRows = $partnerRows;
        $this->view->row = $row;
        $this->view->userRoleJsonData = Zend_Json::encode($userRoleRows);
        $this->view->userRoleProductJsonData = Zend_Json::encode($userRoleProductRows);

        if ($this->_request->isPost()) {
            $field = array();
            $filter = new Zend_Filter_StripTags();
            $password = trim($this->_request->getPost('password'));
            $field['status'] = intval($this->_request->getPost('status'));
            $field['name'] = $filter->filter(trim($this->_request->getPost('name')));
            $field['department'] = $filter->filter(trim($this->_request->getPost('department')));
            $field['mobile'] = $filter->filter(trim($this->_request->getPost('mobile')));
            $field['email'] = $filter->filter(trim($this->_request->getPost('email')));
            $field['type'] = (int)$filter->filter(trim($this->_request->getPost('type')));
            $field['partnerCode'] = $field['type'] == 2 ? $filter->filter(trim($this->_request->getPost('partnerCode'))) : '';
            $roleIds = $this->_request->getPost('roleIds');
            $field['notes'] = $filter->filter(trim($this->_request->getPost('notes')));

            if (strlen($password) > 30 || strlen($password) < 5 && strlen($password) > 0) {
                echo $this->view->message('密码长度不在5-30范围内，请重新填写。') ;
                exit;
            }
            if (strlen($field['name']) == 0) {
                echo $this->view->message('姓名不能为空，请重新填写。') ;
                exit;
            }
            if ($field['mobile'] != '') {
                if (!preg_match("|[0-9]{11}|", $field['mobile'])) {
                    echo $this->view->message('手机号码填写错误。') ;
                    exit;
                }
                if ($this->_model->isExists($field['mobile'], $row['id'])) {
                    echo $this->view->message('手机号已经被其他账户使用，请重新换一个。') ;
                    exit; 
                }
            }
            if ($field['email'] != '') {
                if (!preg_match("/^[a-z]([a-z0-9]*[-_\.]?[a-z0-9]+)*@[a-z0-9]+([-_]?[a-z0-9]+)*(\.[a-z-0-9]{1,10})+$/i", $field['email'])) {
                    echo $this->view->message('E-Mail地址填写错误。') ;
                    exit;
                }
                if ($this->_model->isExists($field['email'], $row['id'])) {
                    echo $this->view->message('E-Mail地址已经被其他账户使用，请重新换一个。') ;
                    exit; 
                }
            }
            if (empty($roleIds)) {
                echo $this->view->message('必须选择一个角色，请重新填写。') ;
                exit;
            }
            foreach($roleIds as $roleId) {
                $isAllProduct = $this->_request->getPost('roleIsAllProduct_' . $roleId) !== NULL ? 1 : 0;
                $userRoleProducts = $this->_request->getPost('userRoleProducts_' . $roleId);
                if ($isAllProduct == 0 && empty($userRoleProducts)) {
                    echo $this->view->message('在选择角色时，必须选择一个角色产品。');
                    exit;
                }
            }

            $passwordMsg = "";
            if ($password != '') {
                $field['password'] = md5($password);
                $passwordMsg = "（密码已修改）";
            }
            //修改
            $this->_model->update($field, "`id` = {$id}");

            //添加角色
            $deleteRoleIds = array_diff($existsRoleIds, $roleIds);
            $insertRoleIds = array_diff($roleIds, $existsRoleIds);
            $updateRoleIds = array_intersect($roleIds, $existsRoleIds);

            if (count($deleteRoleIds) > 0) {
                $userRoleModel->delete("`roleId` IN (". implode(',', $deleteRoleIds) .") AND `userId` = '{$row['id']}'");
                $userRoleProductModel->delete("`roleId` IN (". implode(',', $deleteRoleIds) .") AND `userId` = '{$row['id']}'");
            }
            //插入角色
            if (count($insertRoleIds) > 0) {
                foreach($insertRoleIds as $roleId) {
                    $userRoleField = array();
                    $userRoleField['userId'] = $row['id'];
                    $userRoleField['roleId'] = $roleId;
                    $userRoleField['isAllProduct'] = $this->_request->getPost('roleIsAllProduct_' . $roleId) !== NULL ? 1 : 0;
                    $userRoleModel->insert($userRoleField);
                }
            }
            //更新角色的似乎否不限产品
            if (count($updateRoleIds) > 0) {
                foreach($updateRoleIds as $roleId) {
                    $userRoleField = array();
                    $userRoleField['isAllProduct'] = $this->_request->getPost('roleIsAllProduct_' . $roleId) !== NULL ? 1 : 0;
                    $userRoleModel->update($userRoleField, "`userId` = {$row['id']} AND `roleId` = {$roleId} AND `isAllProduct` <> '{$userRoleField['isAllProduct']}'");
                }
            }
            //插入角色产品
            $allRoleIds = array_merge($insertRoleIds, $updateRoleIds);
            if (count($allRoleIds) > 0) {
                foreach($allRoleIds as $roleId) {
                    $isAllProduct = $this->_request->getPost('roleIsAllProduct_' . $roleId) !== NULL ? 1 : 0;
                    if ($isAllProduct == 0) {
                        //已存在的角色产品
                        $existsRoleProducts = array();
                        $userRoleProductRows = $userRoleProductModel->fetchAll("`userId` = {$row['id']} AND `roleId` = {$roleId}");
                        foreach($userRoleProductRows as $userRoleProductRow) {
                            $existsRoleProducts[] = $userRoleProductRow['productCode'];
                        }
                        //当前需要保存的的角色产品
                        $roleProducts = (array) $this->_request->getPost('userRoleProducts_' . $roleId);

                        //比较
                        $deleteRoleProducts = array_diff($existsRoleProducts, $roleProducts);
                        $insertRoleProducts = array_diff($roleProducts, $existsRoleProducts);

                        if (!empty($deleteRoleProducts)) {
                            $userRoleProductModel->delete("`userId` = {$row['id']} AND `roleId` = {$roleId} AND `productCode` IN ('". implode('\',\'', $deleteRoleProducts) ."')");
                        }
                        foreach($insertRoleProducts as $insertRoleProduct) {
                            $userRoleProductField = array();
                            $userRoleProductField['userId'] = $row['id'];
                            $userRoleProductField['roleId'] = $roleId;
                            $userRoleProductField['productCode'] = $insertRoleProduct;
                            $userRoleProductModel->insert($userRoleProductField);
                        }
                    } else if (!empty($existsRoleIds)) {
                        //如果选择不限产品，则删除所有的此角色的产品
                        $userRoleProductModel->delete("`roleId` = {$roleId} AND `userId` = '{$row['id']}'");
                    }
                }
            }

            $backUrl = $this->_request->get('backUrl') != NULL ? urldecode($this->_request->get('backUrl')) : @$_SERVER['HTTP_REFERER'];
            echo $this->view->message("操作成功{$passwordMsg}。", $backUrl) ;
            exit;
        }
    }

    /**
     * 删除动作
     * 
     * @return void
     */
    public function deleteAction()
    {
        if ($this->_request->isPost()) {
            $ids= $this->_request->getPost('selectId');
            if (is_array($ids)) {
                $this->_model->deleteByIds($ids);
            }
        }
        $backUrl = urldecode($this->_request->get('backUrl'));
        redirect($backUrl);
    }


    /**
     * 修改自己的密码
     * 
     * @return void
     */
    public function updateSelfPasswordAction()
    {
        if ($this->_request->isPost()) {
            $row = array();
            $oldPassword = trim($this->_request->getPost('oldPassword'));
            $password = trim($this->_request->getPost('password'));
            $password2 = trim($this->_request->getPost('password2'));

            if (empty($oldPassword)) {
                echo $this->view->message('请输入原密码。') ;
                exit;
            }
            if (!preg_match("/[A-Z]+/", $password) || !preg_match("/[a-z]+/", $password) || !preg_match("/[0-9]+/", $password)) {
                exit($this->view->message('新密码中必须含有数字，小写字母，大写字母，长度必须在8-30范围内。'));
            }
            if (strlen($password) > 30 || strlen($password) < 8) {
                echo $this->view->message('新密码中必须含有数字，小写字母，大写字母，长度必须在8-30范围内。') ;
                exit;
            }
            if ($password != $password2) {
                echo $this->view->message('确认新密码和新密码填写不一致，请重新填写。') ;
                exit;
            }
            if (md5($oldPassword) != $this->_currentUserRow['password']) {
                echo $this->view->message('原密码填写不正确，请重新填写。') ;
                exit;  
            }
            if (md5($password) == $this->_currentUserRow['password']) {
                echo $this->view->message('所要修改的新密码不能和原密码一致。') ;
                exit;  
            }
            $row['password'] = md5($password);
            $this->_model->update($row, "`id` = {$this->_currentUserRow['id']}");
            echo $this->view->message('修改成功，请重新登录。');
            exit;
        } 
    }

    /**
     * 获取用户角色
     * 
     * @return void
     */
    public function getUserRoleByJsonAction()
    {
        $type = trim($this->_request->get('type'));
        $partnerCode = trim($this->_request->get('partnerCode'));
        if ($type == 1) {
            $roleModel = new Application_Model_Role();
            $roleRows = $roleModel->fetchAll("`type` ='1'", "id DESC");
            echo Zend_Json::encode($roleRows);
        } else {
            $roleModel = new Application_Model_Role();
            $roleRows = $roleModel->fetchAll("`type` = '2' AND `partnerCode` = '{$partnerCode}'", "id DESC");
            echo Zend_Json::encode($roleRows);
        }
        exit;
    }

    /**
     * 检测账户是否存在
     * 
     * @return void
     */
    public function getUserIsExistsByJsonAction()
    {
        $account = trim($this->_request->get('account'));
        $userId = intval($this->_request->get('userId'));
        $isExists = 1;
        if ($account != '') {
            $isExists = $this->_model->isExists($account, $userId);
        }
        exit(Zend_Json::encode($isExists));
    }
}